import 'dart:convert';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_module_pd/SizeUtils.dart';
import 'package:flutter_module_pd/model/Image_model.dart';
import 'package:flutter_module_pd/model/image_data.dart';

import '../dialog/dialog_listener.dart';
import '../dialog/dialog_utils.dart';

class PagerTow extends StatelessWidget {
  const PagerTow({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const MyHomePage();
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> implements OnDialogListener {
  var content = "1";
  final List<String> _list = [];

  var channel;

  @override
  void initState() {
    super.initState();
    //这儿要与MethodChannel(flutterEngine?.dartExecutor, CHANNEL)中CHANNEL名称一致(宿主注册的名字)
    channel = const MethodChannel("tts");

    _getData();
  }

  _refresh() async {
    _list.clear();
    //随机数生成类
    var random = Random();
    for (int i = 0; i < 20; i++) {
      _list.add("item $i == ${random.nextInt(20)}");
    }
    await Future.delayed(const Duration(seconds: 2), () {
      print("我刷新了----");
    });

    //判断页面是否已经销毁
    if (mounted) {
      channel.invokeMethod("showToast", "我刷新成功了--》弹窗提示");
      setState(() {});
    } else {
      print("页面已经被销毁了----");
    }
  }

  _getData() async {
    String json = await rootBundle.loadString("resources/json_data.json");
    ImageModel imageModel = ImageModel.fromJson(jsonDecode(json));
    List<ImageData>? dataList = imageModel.list;
    if (dataList != null) {
      String? message = dataList[0].message;
      print("我的第一个message ------>$message");
    }
  }

  _loading() async {
    //随机数生成类
    var random = Random();
    for (int i = 0; i < 10; i++) {
      _list.add("item $i == ${random.nextInt(20)}");
    }
    await Future.delayed(const Duration(seconds: 2), () {
      print("我刷新了----");
    });
    //判断页面是否已经销毁
    if (mounted) {
      channel.invokeMethod("showToast", "加载更多成功了--》弹窗提示");
      setState(() {});
    } else {
      print("页面已经被销毁了----");
    }
  }

  Widget _listItem(BuildContext context, int index) {
    return Container(
      margin: EdgeInsets.only(top: getHeight(10)),
      child: InkWell(
        onLongPress: () {
          print("显示弹窗++++++");
          showDialogDelete(context, index, _list[index], this);
        },
        child: Row(
          children: [
            Image.network(
              "https://img1.baidu.com/it/u=3057169,121115228&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=753",
              width: getWidth(100),
              height: getHeight(100),
              fit: BoxFit.cover,
            ),
            Expanded(
                child: Column(
              children: [const Text("name"), Text(_list[index])],
            )),
            Image.asset(
              "resources/next.png",
              width: getWidth(40),
              height: getHeight(40),
              fit: BoxFit.contain,
            )
          ],
        ),
      ),
    );
  }

  _onBack() {
    if (Navigator.canPop(context)) {
      Navigator.pop(context, "411111111");
    } else {
      SystemNavigator.pop();
    }
  }

  _getSharedText() {
    //这儿要与 call.method == invokeMethod中invokeMethod名称一致(宿主用于判断回调状态的名字)
    channel.invokeMethod("sst2").then((result) => {
          setState(() {
            content = 'message=>$result';
          })
        });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        //获取状态栏高度 或者使用SafeArea控件
        padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
        child: Column(
          children: <Widget>[
            Container(
              color: Colors.grey.shade200,
              child: Stack(
                alignment: Alignment.centerLeft,
                children: [
                  BackButton(
                    onPressed: _onBack,
                  ),
                  Container(
                    alignment: Alignment.center,
                    child: const Text(
                      "this is page tow",
                      textAlign: TextAlign.center,
                    ),
                  ),
                  InkWell(
                    child: Container(
                      margin: EdgeInsets.only(right: getWidth(20)),
                      alignment: Alignment.centerRight,
                      child: const Text("菜单"),
                    ),
                    onTap: () {
                      showDialogMenu(context);
                    },
                  )
                ],
              ),
            ),
            Expanded(
              child: EasyRefresh(
                  firstRefresh: true,
                  onRefresh: () async {
                    await _refresh();
                  },
                  onLoad: () async {
                    await _loading();
                  },
                  child: ListView.builder(
                      itemCount: _list.length,
                      itemBuilder: (context, index) {
                        return _listItem(context, index);
                      })),
            ),
            GestureDetector(
              onTap: _getSharedText,
              child: Container(
                alignment: Alignment.center,
                width: getWindWidth(),
                height: getHeight(50),
                color: Colors.amberAccent,
                child: Text(
                  'this is my base pager Tow -- $content',
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  void onCancel() {
    print("删除取消");
  }

  @override
  void onConfirm() {
    print("删除确定");
  }
}
